package com.starbaba.weixin.view;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.base.common.database.BaseDao;
import com.base.common.log.LogService;
import com.base.common.util.RandomUtils;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.controllog.model.ControlLogCategory;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.constant.WebConstants;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.util.QueryListUtil;
import com.starbaba.weixin.model.StatweixinCouponFollow;
import com.starbaba.weixin.model.Weixin_coupon;
import com.starbaba.weixin.service.WeixinCouponService;

public class WeixinCouponAction extends BaseAction implements ModelDriven<Weixin_coupon> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8116797708161870937L;

	private Weixin_coupon model;

	private WeixinCouponService server;
	
    private Map<String, Object> responseMap;

	private ArrayList<ControlLogCategory> logCategorysArrayList;

	public WeixinCouponAction() {
		logCategorysArrayList = new ArrayList<ControlLogCategory>();
	}

	public String showPage() {
		List<String> channelList = new ArrayList<String>();
		List<String> keyWordsList = new ArrayList<String>();
		List<Weixin_coupon> wlist = server.getWCResult();
		if (wlist != null) {
			for (Weixin_coupon w_coupon : wlist) {
				channelList.add(w_coupon.getChannel());
				keyWordsList.add(w_coupon.getKeyword());
			}
		}
		model.setChannelList(channelList);
		model.setKeywordsList(keyWordsList);
		return "success";
	}
	public void query() {
		parsePageRequest();
		try {
			PageResponse pageResponse = new PageResponse();
			List list = server.getDataList(pageRequest.getIDisplayStart(), pageRequest.getIDisplayLength(), model, pageResponse, getService());
			pageResponse.setAaData(list);
			pageResponse.setSEcho(pageRequest.getSEcho());
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String add() {
		responseMap = new HashMap<>();
		Map<String, Object> params = QueryListUtil.getRequestParamsMap(ServletActionContext.getRequest());
		QueryListUtil.dropEmptyParams(params);

		try {
			String keyword = (String) params.get("keyword");
			String channel = (String) params.get("channel");
			String fuel_coupon_id = (String) params.get("fuel_coupon_id");
			Integer coupon_type = Integer.valueOf((String) params.get("coupon_type"));
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
			String ticket = "weixin_coupon_" + RandomUtils.getRandomAlphaString(10)+ format.format(new Date()) + "_ticket";
			Weixin_coupon w_coupon = new Weixin_coupon();
			w_coupon.setChannel(channel);
			w_coupon.setKeyword(keyword);
			w_coupon.setCreatetime(new Date());
			w_coupon.setCoupon_type(coupon_type);
			w_coupon.setFuel_coupon_id(fuel_coupon_id);
			w_coupon.setTicket(ticket);
			BaseDao dao = new BaseDao(Constant.POOL_LIFE);
			dao.add(w_coupon);

		} catch (Exception e) {
			LogService.error(e);
			responseMap.put("status", -1);
			responseMap.put("msg", e.getMessage());
			return SUCCESS;
		}
		responseMap.put("status", 1);
		responseMap.put("msg", "添加成功");
		return SUCCESS;
	}
	public void queryById() {
        responseMap = new HashMap<>();
        HttpServletRequest request = ServletActionContext.getRequest();

        String id = request.getParameter("id");

        BaseDao baseDao = new BaseDao(Constant.POOL_LIFE);
        try {
            Weixin_coupon m = baseDao.get("select * from loan.weixin_activity_coupon i where i.id = ?", Weixin_coupon.class, id);
            if (m != null) {
                responseMap.put("data", m);
            }
        } catch (Exception e) {
            LogService.error( e);
            responseMap.put("status", -1);
        }
        responseMap.put("status", 0);
        try {
			sendJsonMessage(JsonUtils.toJson(responseMap, null, true, null, false));
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

	public String update() {
		responseMap = new HashMap<>();
		Map<String, Object> params = QueryListUtil.getRequestParamsMap(ServletActionContext.getRequest());
		QueryListUtil.dropEmptyParams(params);
		try {
			Long id = Long.valueOf((String) params.get("id"));
			String keyword = (String) params.get("keyword");
			String channel = (String) params.get("channel");
			String fuel_coupon_id = (String) params.get("fuel_coupon_id");
			Integer coupon_type = Integer.valueOf((String) params.get("coupon_type"));
			
			Weixin_coupon w_coupon = new Weixin_coupon();
			w_coupon.setId(id);
			w_coupon.setChannel(channel);
			w_coupon.setKeyword(keyword);
			w_coupon.setCreatetime(new Date());
			w_coupon.setCoupon_type(coupon_type);
			w_coupon.setFuel_coupon_id(fuel_coupon_id);
			
			BaseDao baseDao = new BaseDao(Constant.POOL_LIFE);
			baseDao.update(w_coupon, "id");
		} catch (Exception e) {
			LogService.error(e);
			responseMap.put("status", -1);
			responseMap.put("msg", e.getMessage());
			return SUCCESS;
		}

		responseMap.put("status", 1);
		responseMap.put("msg", "更新成功");
		return SUCCESS;
	}
	
	/** 统计 */
	public String weixinCouponStatView() {
		List<String> channelList = new ArrayList<String>();
		List<Weixin_coupon> wlist = server.getWCResult();
		if (wlist != null) {
			for (Weixin_coupon w_coupon : wlist) {
				channelList.add(w_coupon.getChannel());
			}
		}
		model.setChannelList(channelList);
		return "success";
	}
	
	public void weixinCouponStat() {
        parsePageRequest();
        PageResponse pageResponse = new PageResponse();
        
        HttpServletRequest request = ServletActionContext.getRequest();
        String channel = request.getParameter("channel");
        String startTimeStr = request.getParameter("startTime");
        String endTimeStr = request.getParameter("endTime");
        StringBuffer sqlBuffer  = new StringBuffer();
        List<Object> params = new ArrayList<Object>();
        sqlBuffer.append("select * from loan.stat_weixin_new_coupon_follow i where 1=1 ");
        if(!StringUtils.isEmpty(channel)){
        	sqlBuffer.append(" and i.channel = ? ");
        	params.add(channel);
        }
        
        if(!StringUtils.isEmpty(startTimeStr)){
        	sqlBuffer.append(" and i.rtime >= ? ");
        	params.add(startTimeStr);
        }
        
        if(!StringUtils.isEmpty(endTimeStr)){
        	sqlBuffer.append(" and i.rtime <= ? ");
        	params.add(endTimeStr);
        }
        sqlBuffer.append(" order by rtime desc ");
        String sql = sqlBuffer.toString();
        BaseDao baseDao = new BaseDao(Constant.POOL_PUSH_RW);
        try {
        	List m = baseDao.list(sql,StatweixinCouponFollow.class,params);
        	pageResponse.setAaData(m);
        	pageResponse.setITotalRecords(m.size());
        	pageResponse.setITotalDisplayRecords(m.size());
			pageResponse.setSEcho(pageRequest.getSEcho());
			sendJsonMessage(JsonUtils.toJson(pageResponse, null, true, null, false));
		} catch (Exception e) {
			e.printStackTrace();
		}
    }

	protected void sendJsonMessage(String jsonMessage) throws IOException {
		HttpServletResponse response = Struts2Utils.getResponse();
		response.setCharacterEncoding(WebConstants.CHARACTER_ENCODING_UTF_8);
		response.getWriter().write(jsonMessage);
		response.flushBuffer();
	}
	
	@Override
	public Weixin_coupon getModel() {
		if (model == null) {
			model = new Weixin_coupon();
		}

		return model;
	}

	@Autowired
	@Qualifier("weixinCouponServcieImpl")
	public void setServer(WeixinCouponService server) {
		this.server = server;
	}

	@Override
	public ArrayList<ControlLogCategory> getProduct() {
		return logCategorysArrayList;
	}

}
